package com.example.sfm.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.example.sfm.constant.MessageConstants;
import com.example.sfm.pojo.dto.AwardsPunishmentsDto;
import com.example.sfm.pojo.dto.AwardsPunishmentsImportDto;
import com.example.sfm.pojo.dto.AwardsPunishmentsQueryDto;
import com.example.sfm.result.Result;
import com.example.sfm.service.IAwardsPunishmentsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author sfm
 * @since 2025-03-07
 */
@Tag(name = "管理员奖惩管理")
@RestController("adminAwardsPunishmentsController")
@RequestMapping("/admin/awards-punishments")
@RequiredArgsConstructor
@Slf4j
public class AwardsPunishmentsController {
    private final IAwardsPunishmentsService apService;

    /**
     * 创建奖惩记录
     */
    @Operation(summary = "创建奖惩记录")
    @PostMapping("/create")
    public Result<?> createRecord(@RequestBody @Validated @Parameter(description = "奖惩记录信息") AwardsPunishmentsDto dto) {
        log.info("创建奖惩记录: {}", dto);
        apService.createRecord(dto);
        return Result.success(MessageConstants.ADD_OK);
    }

    /**
     * 分页查询记录
     */
    @Operation(summary = "分页查询奖惩记录")
    @GetMapping("/list")
    public Result<?> listRecords(@ParameterObject AwardsPunishmentsQueryDto dto) {
        log.info("查询奖惩记录: {}", dto);
        return Result.success(apService.listRecords(dto), MessageConstants.SELECT_OK);
    }

    /**
     * 更新记录
     */
    @Operation(summary = "更新奖惩记录")
    @PutMapping("/update/{id}")
    public Result<?> updateRecord(@PathVariable @Parameter(description = "奖惩记录ID",in = ParameterIn.PATH) Integer id,
                                  @RequestBody @Validated @Parameter(description = "更新内容") AwardsPunishmentsDto dto) {
        log.info("更新记录: ID={}, 内容={}", id, dto);
        apService.updateRecord(id, dto);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    /**
     * 批量删除记录
     */
    @Operation(summary = "批量删除奖惩记录")
    @DeleteMapping("/delete")
    public Result<?> deleteRecords(@RequestParam @Parameter(description = "奖惩记录ID列表",in = ParameterIn.QUERY) List<Integer> ids) {
        log.info("批量删除记录: IDs={}", ids);
        apService.deleteRecords(ids);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    /**
     * 下载导入模板
     */
    @Operation(summary = "下载奖惩记录导入模板")
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        try {
            // 设置响应头
            String fileName = URLEncoder.encode("奖惩记录导入模板_" + LocalDate.now(), StandardCharsets.UTF_8);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 使用EasyExcel生成模板（无数据，只有表头）
            EasyExcel.write(response.getOutputStream(), AwardsPunishmentsImportDto.class)
                    .sheet("奖惩记录")
                    .doWrite(Collections.emptyList());

        } catch (Exception e) {
            log.error("模板下载失败", e);
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(Result.error(400,"模板下载失败：" + e.getMessage()));
        }
    }

    @Operation(summary = "导入奖惩记录")
    @PostMapping("/import")
    public Result<?> importExcel(@RequestParam @Parameter(description = "上传的Excel文件") MultipartFile file) {
        apService.importFromExcel(file);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    @Operation(summary = "导出奖惩记录")
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response, @ParameterObject AwardsPunishmentsQueryDto dto) {
        apService.exportExcel(response, dto);
    }

    @Operation(summary = "获取奖惩记录统计信息")
    @GetMapping("/stats")
    public Result<?> getStats(@RequestParam(required = false) @Parameter(description = "学生ID",in = ParameterIn.QUERY) Integer studentId) {
        return Result.success(apService.getStats(studentId));
    }
}